package com.luzhikun.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author Rookie Coder
 * @Description Mybatis连接工具层
 * @Date
 **/
public class SqlSessionUtil {
   private static SqlSessionFactory sqlSessionFactory;
    private SqlSessionUtil(){};
    static {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
         sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
    }

    private static ThreadLocal<SqlSession> sqlSessionThreadLocal=new ThreadLocal<>();

    public static SqlSession getSqlSession(){

        SqlSession sqlSession = sqlSessionThreadLocal.get();

        if (sqlSession==null){
            sqlSession=sqlSessionFactory.openSession(true);
            sqlSessionThreadLocal.set(sqlSession);
        }

        return sqlSession;
    }

    public static void closeAll(SqlSession sqlSession){

        if (sqlSession!=null){

            // 关闭sqlSession连接
            sqlSession.close();

            // 从线程池中移除
            sqlSessionThreadLocal.remove();

        }

    }


}
